#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
int money=5000;
//1、创建互斥锁
pthread_mutex_t mu;
void* test1(void*);
void* test2(void*);
int main()
{
	//2、初始化互斥锁
	pthread_mutex_init(&mu,NULL);
	pthread_t p1,p2;
	if(pthread_create(&p1,NULL,test1,NULL)!=0){perror("创建失败:");return -1;}
	if(pthread_create(&p2,NULL,test2,NULL)!=0){perror("创建失败:");return -1;}
	printf("p1=%#lx\np2=%#lx\n",p1,p2);
	printf("阻塞等待p1\n");
	pthread_join(p1,NULL);
	printf("阻塞等待p2\n");
	pthread_join(p2,NULL);
	pthread_mutex_destroy(&mu);
	printf("全部结束\n");
	return 0;
}
//
void* test1(void*)
{
	while(1)
	{
		printf("张三等待互斥锁\n");
		//3、获取锁资源
		pthread_mutex_lock(&mu);
		if(money<200)
		{
			//4、释放锁资源
			pthread_mutex_unlock(&mu);
			break;
		}
		else
		{
			//sleep(1);
			money-=200;
			printf("张三取走200元，余额：%d\n\n",money);
			//4、释放锁资源
			pthread_mutex_unlock(&mu);
		}
	}
}
void* test2(void*)
{
	while(1)
	{
		printf("李四等待互斥锁\n");
		//3、获取锁资源
		pthread_mutex_lock(&mu);
		if(money<500)
		{
			//4、释放锁资源
			pthread_mutex_unlock(&mu);
			break;
		}
		else
		{
			//sleep(1);
			money-=500;
			printf("李四取走500元，余额：%d\n\n",money);
			//4、释放锁资源
			pthread_mutex_unlock(&mu);
		}
	}
}
